<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>URU4500 Enroll & Verify</title>
        <link rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
        <link rel="stylesheet"
            href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
        <link rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/sweetalert2@11.11.0/dist/sweetalert2.min.css">
        <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
        <script
            src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
        <script
            src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <script
            src="https://cdn.jsdelivr.net/npm/moment@2/min/moment.min.js"></script>
        <script
            src="https://cdn.jsdelivr.net/npm/moment-timezone@0.5.43/builds/moment-timezone-with-data.min.js"></script>
        <style>
        body { background: #f6f8fc; }
        .card-profile { min-width: 300px; }
        .vertical-divider { border-left: 2px solid #eee; height: 100%; }
        .form-label { margin-top: 8px; }
        .enroll-section, .verify-section { background: #fff; border-radius: 1.5rem; box-shadow: 0 0 16px #e7eaf3; padding: 2rem; }
    </style>
    </head>
    <body>
        {% include 'navbar.html' %}
        <div class="container py-5">
            <div class="row g-5">
                <!-- ENROLL (LEFT) -->
                <div class="col-md-5">
                    <div class="enroll-section">
                        <h4 class="mb-3">🔒 Enroll ผู้ใช้งานใหม่ (5
                            ตัวอย่าง)</h4>
                        <form id="enroll-form" enctype="multipart/form-data">
                            <div class="mb-3">
                                <label class="form-label">รหัสนักเรียน</label>
                                <input name="student_code" class="form-control"
                                    required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">ชื่อ-นามสกุล</label>
                                <input name="fullname" class="form-control"
                                    required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">ชั้นปี</label>
                                <input name="year" class="form-control"
                                    required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">สังกัด</label>
                                <input name="department" class="form-control"
                                    required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">รูปถ่าย</label>
                                <input type="file" name="photo"
                                    class="form-control" accept="image/*"
                                    required>
                            </div>
                            <button type="button" id="enroll-btn"
                                class="btn btn-primary w-100" disabled>Enroll
                                (Scan 5 ครั้ง)</button>
                        </form>
                        <div id="enroll-result" class="mt-3"></div>
                    </div>
                </div>

                <!-- DIVIDER -->
                <div
                    class="col-md-1 d-none d-md-flex align-items-center justify-content-center">
                    <div class="vertical-divider"></div>
                </div>

                <!-- VERIFY (RIGHT) -->
                <div class="col-md-6">
                    <div class="verify-section">
                        <h4 class="mb-3">🔍 Verify นิ้วมือ</h4>
                        <div class="input-group mb-3">
                            <input id="verify_code" class="form-control"
                                placeholder="กรอกรหัสนักเรียน หรือ Scan"
                                autocomplete="off">
                            <button id="verify-scan-btn" class="btn btn-success"
                                type="button">Scan & Verify</button>
                        </div>
                        <div id="verify-profile-card" class="mb-3"></div>
                        <h5 class="mt-4">ผลการ Verify ล่าสุด</h5>
                        <table id="verify-history"
                            class="table table-striped table-bordered align-middle"
                            style="width:100%;">
                            <thead>
                                <tr>
                                    <th>เวลา</th>
                                    <th>รหัส</th>
                                    <th>ชื่อ-สกุล</th>
                                    <th>ชั้นปี</th>
                                    <th>สังกัด</th>
                                    <th>ผลลัพธ์</th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                    <hr>
                    <button id="reset-device-btn"
                        class="btn btn-warning col-md-12">
                        🔄 Reset Device
                    </button>
                    <script>
                        $("#reset-device-btn").click(function() {
                            Swal.fire({
                                title: "Reset Device?",
                                text: "ต้องการรีเซ็ตเครื่องอ่านลายนิ้วมือหรือไม่?",
                                icon: "warning",
                                showCancelButton: true,
                                confirmButtonText: "รีเซ็ต",
                                cancelButtonText: "ยกเลิก"
                            }).then((result) => {
                                if(result.isConfirmed){
                                    $.ajax({
                                        url: "/api/reset_device",
                                        type: "POST",
                                        success: function(res){
                                            if(res.success){
                                                Swal.fire("Success", res.msg, "success");
                                            }else{
                                                Swal.fire("Error", res.msg, "error");
                                            }
                                        },
                                        error: function(){
                                            Swal.fire("Error", "ไม่สามารถรีเซ็ต device ได้", "error");
                                        }
                                    });
                                }
                            });
                        });
                    </script>
                </div>

                <!-- User Data Table for Deletion -->
                <!-- ตาราง Users แบบ DataTables (ใต้อะไรก็ได้ในหน้า) -->
                <div class="mt-4">
                    <h5>รายชื่อผู้ใช้ทั้งหมด</h5>
                    <table id="user-list"
                        class="table table-bordered table-hover align-middle"
                        style="width:100%;">
                        <thead>
                            <tr>
                                <th>รหัสนักเรียน</th>
                                <th>ชื่อ-นามสกุล</th>
                                <th>ชั้นปี</th>
                                <th>สังกัด</th>
                                <th>รูปภาพ</th>
                                <th>ลบ</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <script>
$(function(){
    // Bootstrap enable Enroll button only when all fields filled
    $("#enroll-form input").on('input change', function(){
        let filled = true;
        $("#enroll-form input[required]").each(function(){
            if(!$(this).val()) filled = false;
        });
        $("#enroll-btn").prop("disabled", !filled);
    });

    $("#enroll-btn").click(function(){
        let formData = new FormData($("#enroll-form")[0]);
        $("#enroll-result").html('<div class="alert alert-info">กำลังอ่านนิ้วมือ 5 ครั้ง ...</div>');
        $.ajax({
            url: "/enroll",
            type: "POST",
            data: formData,
            contentType: false,
            processData: false,
            success: function(res){
                if(res.success){
                    $("#enroll-result").html('<div class="alert alert-success">บันทึกผู้ใช้เรียบร้อย!<br>User ID: '+res.user_id+'<br>Enroll 5 samples OK</div>');
                    $("#enroll-form")[0].reset();
                    $("#enroll-btn").prop("disabled", true);
                }else{
                    $("#enroll-result").html('<div class="alert alert-danger">'+res.error+'</div>');
                }
            }
        });
    });

    // Verify scan logic
    let historyTable = $('#verify-history').DataTable({
        columns: [
            { title: "เวลา" },
            { title: "รหัส" },
            { title: "ชื่อ-สกุล" },
            { title: "ชั้นปี" },
            { title: "สังกัด" },
            { title: "ผลลัพธ์" }
        ],
        order: [[0, "desc"]]
    });
    function showProfileCard(profile){
        let imgsrc = profile.photo ? `data:image/jpeg;base64,${profile.photo}` : "";
        return `
            <div class="card card-profile shadow-sm mb-3">
                <div class="row g-0">
                    <div class="col-4 text-center align-self-center">
                        <img src="${imgsrc}" alt="photo" class="rounded-circle img-fluid" style="width:100px;height:100px;object-fit:cover;">
                    </div>
                    <div class="col-8">
                        <div class="card-body">
                            <h5 class="card-title">${profile.fullname}</h5>
                            <p class="card-text mb-1"><b>รหัส:</b> ${profile.student_code}</p>
                            <p class="card-text mb-1"><b>สังกัด:</b> ${profile.department}</p>
                            <p class="card-text"><small class="text-muted">UserID: ${profile.id}</small></p>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    $("#verify-scan-btn").click(function(){
        let code = $("#verify_code").val();
        $("#verify-profile-card").html('<div class="alert alert-info">กำลังตรวจสอบนิ้วมือ ...</div>');
        $.ajax({
            url: "/verify_by_code",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({student_code: code}),
            success: function(res){
                if(res.success){
                    $("#verify-profile-card").html(showProfileCard(res.profile));
                    // Append to datatable
                    historyTable.row.add([
                        moment.tz(new Date(), "UTC").format("YYYY-MM-DD HH:mm:ss"),
                        res.profile.student_code,
                        res.profile.fullname,
                        res.profile.year,
                        res.profile.department,
                        `<span class="badge bg-success">✔ Verified</span>` + (res.score !== undefined && res.score !== null ? (({{ FP_SCORE_THRESHOLD }} - res.score) / {{ FP_SCORE_THRESHOLD }} * 100).toFixed(1) + "%" : ""),
                    ]).draw(false);
                }else{
                    $("#verify-profile-card").html('<div class="alert alert-danger">'+res.error+'</div>');
                }
            }
        });
    });

    // โหลด Users ทั้งหมดจาก backend (API)
    function loadAllUsers() {
        $.get("/all_users_json", function(users){
            let rows = [];
            users.forEach(u => {
                let imgTag = u.photo ? `<img src="data:image/jpeg;base64,${u.photo}" class="rounded-circle" style="width:50px;height:50px;object-fit:cover;">` : "";
                rows.push([
                    u.student_code,
                    u.fullname,
                    u.year,
                    u.department,
                    imgTag,
                    `<button class="btn btn-danger btn-sm delete-btn" data-user-id="${u.id}">ลบ</button>`
                ]);
            });
            let table = $("#user-list").DataTable();
            table.clear().rows.add(rows).draw();
        });
    }


    // Handle Delete Button
    $("#user-list").on("click", ".delete-btn", function(){
        let user_id = $(this).data("user-id");
        // ดึงข้อมูล user profile มาก่อน (แนะนำใช้ API เดียวกับ /all_users_json หรือ /user_profile/:id)
        $.get("/user_profile/"+user_id, function(res){
            if(res.success){
                let p = res.profile;
                Swal.fire({
                    title: "ยืนยันการลบผู้ใช้",
                    html: `
                        <img src="data:image/jpeg;base64,${p.photo}" class="rounded-circle mb-2" style="width:80px;height:80px;object-fit:cover;">
                        <div><b>${p.fullname}</b></div>
                        <div>${p.department}</div>
                        <input type="password" id="delete-pin" class="swal2-input mt-2" placeholder="PIN สำหรับลบข้อมูล">
                    `,
                    showCancelButton: true,
                    confirmButtonText: 'ยืนยันลบ',
                    cancelButtonText: 'ยกเลิก',
                    preConfirm: () => {
                        const pin = Swal.getPopup().querySelector('#delete-pin').value
                        if (!pin) {
                            Swal.showValidationMessage('กรุณาใส่ PIN')
                        }
                        return { pin: pin }
                    }
                }).then((result) => {
                    if(result.isConfirmed && result.value && result.value.pin){
                        $.ajax({
                            url: "/delete_user",
                            type: "POST",
                            contentType: "application/json",
                            data: JSON.stringify({user_id: user_id, pin: result.value.pin}),
                            success: function(del){
                                if(del.success){
                                    Swal.fire("ลบข้อมูลเรียบร้อย!", "", "success");
                                    loadAllUsers();
                                }else{
                                    Swal.fire("ผิดพลาด", del.error, "error");
                                }
                            }
                        });
                    }
                });
            }
        });
    });

    $('#user-list').DataTable({
        columns: [
            { title: "รหัสนักเรียน" },
            { title: "ชื่อ-นามสกุล" },
            { title: "ชั้นปี" },
            { title: "สังกัด" },
            { title: "รูปภาพ", orderable: false, searchable: false },
            { title: "ลบ", orderable: false, searchable: false }
        ],
        order: [[0, "desc"]]
    });
    loadAllUsers();
});
</script>
    </body>
</html>
